<template>
  <div>
    <el-card class="!border-none mb-4" shadow="never">
      <el-form class="mb-[-16px]" :model="queryParams" inline>
        <!--        <el-form-item label="设备信息">-->
        <!--          <el-cascader-->
        <!--              :options="optionsData.device"-->
        <!--              clearable-->
        <!--              v-model="queryParams.device"-->
        <!--              filterable-->
        <!--              :props="{-->
        <!--                checkStrictly: true-->
        <!--              }"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item label="科室信息">
          <el-cascader
              :options="optionsData.department"
              v-model="queryParams.department"
              filterable clearable
              :props="{
                checkStrictly: true
              }"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select class="w-[280px]" v-model="queryParams.status">
            <el-option label="全部" value/>
            <el-option label="显示" :value="1"/>
            <el-option label="隐藏" :value="0"/>
          </el-select>
        </el-form-item>
        <el-form-item label="最后记录时间">
          <daterange-picker
              v-model:startTime="queryParams.create_time_start"
              v-model:endTime="queryParams.create_time_end"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="resetPage">查询</el-button>
          <el-button @click="resetParams">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="!border-none" v-loading="pager.loading" shadow="never">
      <!--            <el-button v-perms="['room_department_device/add']" type="primary" @click="handleAdd">-->
      <!--                <template #icon>-->
      <!--                    <icon name="el-icon-Plus" />-->
      <!--                </template>-->
      <!--                新增设备-->
      <!--            </el-button>-->
      <el-button :disabled="!selectData.length" type="primary" @click="handleCopyS(selectData)">
        <template #icon>
          <icon name="el-icon-Plus"/>
        </template>
        新增水表
      </el-button>
      <el-button :disabled="!selectData.length" type="primary" @click="handleCopyD(selectData)">
        <template #icon>
          <icon name="el-icon-Plus"/>
        </template>
        新增电表
      </el-button>
      <el-button :disabled="!selectData.length" @click="handleDelete(selectData)">
        删除
      </el-button>

      <el-button type="warning" @click="monthInit">
        <template #icon>
          <icon name="el-icon-Plus"/>
        </template>
        月初始化
      </el-button>

      <div class="mt-4">
        <el-table :data="pager.lists" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"/>
          <el-table-column label="序号" prop="sort" width="90" fixed="left" show-overflow-tooltip/>
          <el-table-column label="科室信息" prop="rid" width="200" fixed="left">
            <template #default="{ row }">
              <view v-if="row.room">
                {{ row.room.name }}
                <view v-if="row.campus"><br/> {{ row.campus.name }}</view>
                <view v-if="row.building"><br/> {{ row.building.name }}</view>
              </view>
            </template>
          </el-table-column>

          <el-table-column label="设备信息" prop="device_name" width="200">
            <template #default="{ row }">
              <!--              <view v-if="row.device_name">-->
              <view v-if="row.device_name">
                {{ row.device_name }} <br/>
              </view>
              <view v-if="row.device_no">
                {{ row.device_no }} <br/>
              </view>
              <view v-if="row.device_type_text">
                {{ row.device_type_text }}
              </view>
              <!--              </view>-->
            </template>
          </el-table-column>

          <!--                    <el-table-column label="科室信息" prop="departments" show-overflow-tooltip width="200" />-->
          <!--                    <el-table-column label="设备信息" prop="devices" show-overflow-tooltip width="200" />-->
          <!--                    <el-table-column label="设备类型" prop="devices_type" show-overflow-tooltip width="100" />-->

          <el-table-column label="底数" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.base_number"
                        :placeholder="scope.row.get_enter"
                        @focus="changeColor(scope.row,scope.$index,'base_number')"
                        @click="clearInput(scope.row, 'base_number')"
                        @blur="setNullInput(scope.row, 'base_number')"
                        @keyup.enter="newEnter(scope.row,scope.$index, 'base_number')"
                        :ref="(el:refItem) => handleSetInputMap(el, scope.$index,'base_number')"
                        :class="editIndex == 'base_number'+scope.$index ? 'current_color':''"
              />
            </template>
          </el-table-column>
          <el-table-column label="读数" width="150">
            <template #default="scope">
              <!--@change="setSave(scope.row,scope.$index,'reading')"-->
              <el-input v-model="scope.row.reading"
                        :placeholder="scope.row.get_enter"
                        @focus="changeColor(scope.row, scope.$index,'reading')"
                        @click="clearInput(scope.row, 'reading')"
                        @blur="setNullInput(scope.row, 'reading')"
                        @keyup.enter="newEnter(scope.row, scope.$index, 'reading')"
                        :ref="(el:refItem) => handleSetInputMap(el, scope.$index,'reading')"
                        :class="editIndex == 'reading'+scope.$index ? 'current_color' : ''"
              />
            </template>
          </el-table-column>

          <!--                    <el-table-column label="计费量" width="150">-->
          <!--                        <template #default="{ row }">-->
          <!--                            <el-input-->
          <!--                                v-model="row.use_total"-->
          <!--                                @blur="editField('use_total', row.use_total, row.id)"-->
          <!--                            />-->
          <!--                        </template>-->
          <!--                    </el-table-column>-->
          <el-table-column label="使用量" prop="use_total" show-overflow-tooltip width="150"/>

          <el-table-column label="系数" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.coefficient"
                        :placeholder="scope.row.get_enter"
                        @focus="changeColor(scope.row,scope.$index,'coefficient')"
                        @click="clearInput(scope.row, 'coefficient')"
                        @blur="setNullInput(scope.row, 'coefficient')"
                        @keyup.enter="newEnter(scope.row,scope.$index, 'coefficient')"
                        :ref="(el:refItem) => handleSetInputMap(el, scope.$index,'coefficient')"
                        :class="editIndex == 'coefficient'+scope.$index ? 'current_color':''"/>
            </template>
          </el-table-column>
          <el-table-column label="价格" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.price"
                        :placeholder="scope.row.get_enter"
                        @focus="changeColor(scope.row,scope.$index,'price')"
                        @click="clearInput(scope.row, 'price')"
                        @blur="setNullInput(scope.row, 'price')"
                        @keyup.enter="newEnter(scope.row,scope.$index, 'price')"
                        :ref="(el:refItem) => handleSetInputMap(el, scope.$index,'price')"
                        :class="editIndex == 'price'+scope.$index ? 'current_color':''"/>
            </template>
          </el-table-column>

          <!--                    <el-table-column label="费用" width="150">-->
          <!--                        <template #default="{ row }">-->
          <!--                            <el-input-->
          <!--                                v-model="row.total_fee"-->
          <!--                                @blur="editField('total_fee', row.total_fee, row.id)"-->
          <!--                            />-->
          <!--                        </template>-->
          <!--                    </el-table-column>-->
          <el-table-column label="总费用" prop="total_fee" show-overflow-tooltip width="150"/>

          <!--          <el-table-column label="电梯费" width="150">-->
          <!--            <template #default="scope">-->
          <!--              <el-input v-model="scope.row.lift_fee"-->
          <!--                        :placeholder="scope.row.get_enter"-->
          <!--                        @focus="changeColor(scope.row,scope.$index,'lift_fee')"-->
          <!--                        @click="clearInput(scope.row, 'lift_fee')"-->
          <!--                        @blur="setNullInput(scope.row, 'lift_fee')"-->
          <!--                        @keyup.enter="newEnter(scope.row,scope.$index, 'lift_fee')"-->
          <!--                        :ref="(el:refItem) => handleSetInputMap(el, scope.$index,'lift_fee')"-->
          <!--                        :class="editIndex == 'lift_fee'+scope.$index ? 'current_color':''"/>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <!--          <el-table-column label="二次加压费" width="150">-->
          <!--            <template #default="scope">-->
          <!--              <el-input-->
          <!--                  v-model="scope.row.second_pressure_fee"-->
          <!--                  :placeholder="scope.row.get_enter"-->
          <!--                  @focus="changeColor(scope.row,scope.$index,'second_pressure_fee')"-->
          <!--                  @click="clearInput(scope.row, 'second_pressure_fee')"-->
          <!--                  @blur="setNullInput(scope.row, 'second_pressure_fee')"-->
          <!--                  @keyup.enter="newEnter(scope.row,scope.$index, 'second_pressure_fee')"-->
          <!--                  :ref="(el:refItem) => handleSetInputMap(el, scope.$index,'second_pressure_fee')"-->
          <!--                  :class="editIndex == 'second_pressure_fee'+scope.$index ? 'current_color':''"/>-->
          <!--            </template>-->
          <!--          </el-table-column>-->

          <el-table-column label="最后记录时间" prop="log_time" show-overflow-tooltip width="130"/>
          <!--          <el-table-column label="初始化" min-width="100" fixed="right">-->
          <!--            <template #default="{ row }">-->
          <!--              <el-tag :type="row.is_init == 1 ? 'success' : 'warning'">{{-->
          <!--                  row.init_text-->
          <!--                }}-->
          <!--              </el-tag>-->
          <!--            </template>-->
          <!--          </el-table-column>-->

          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button v-if="row.room_master != 1" type="danger" size="small" @click="handleDelete(row.id)">
                删除
              </el-button>
              <el-button v-if="row.room_master == 1" type="warning" size="small" @click="handleCopyS(row.id)">
                新增水表
              </el-button>
              <el-button v-if="row.room_master == 1" type="warning" size="small" @click="handleCopyD(row.id)">
                新增电表
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="flex mt-4 justify-end">
        <pagination v-model="pager" @change="getLists"/>
      </div>
    </el-card>
    <edit-popup
        v-if="showEdit"
        ref="editRef"
        :dict-data="dictData"
        @success="getLists"
        @close="showEdit = false"
    />
  </div>
</template>

<script lang="ts" setup name="roomDepartmentDeviceLists">
import {usePaging} from '@/hooks/usePaging'
import {useDictData} from '@/hooks/useDictOptions'
import {
  apiRoomDepartmentDeviceLists,
  apiRoomDepartmentDeviceDelete,
  roomDepartmentDeviceStatus,
  roomDepartmentDeviceInit,
  roomDeviceAll,
  departmentAll,
  editFieldItem,
  roomDepartmentDeviceCopy,
  apiRoomDepartmentDeviceSave,
} from '@/api/room/room_department_device'
import {timeFormat} from '@/utils/util'
import feedback from '@/utils/feedback'
import EditPopup from './edit.vue'
import {useDictOptions} from '@/hooks/useDictOptions'

const editRef = shallowRef<InstanceType<typeof EditPopup>>()
// 是否显示编辑框
const showEdit = ref(false)

type refItem = Element | null
const editIndex = ref('');
const inputRefMap = ref({});
const props1 = {
  checkStrictly: true
}
const {optionsData} = useDictOptions<{
  device: any[]
  department: any[]
}>({
  device: {
    api: roomDeviceAll
  },
  department: {
    api: departmentAll
  }
})

// 查询条件
const queryParams = reactive({
  status: '',
  device: [],
  create_time_start: '',
  create_time_end: '',
  department: []
})

// 选中数据
const selectData = ref<any[]>([])

// 表格选择后回调事件
const handleSelectionChange = (val: any[]) => {
  selectData.value = val.map(({id}) => id)
}

// 获取字典数据
const {dictData} = useDictData('')

// 分页相关
const {pager, getLists, resetParams, resetPage} = usePaging({
  fetchFun: apiRoomDepartmentDeviceLists,
  params: queryParams
})

const changeStatus = async (status: any, id: number) => {
  try {
    await roomDepartmentDeviceStatus({id, status})
    getLists()
  } catch (error) {
    getLists()
  }
}

// 添加
const handleAdd = async () => {
  showEdit.value = true
  await nextTick()
  editRef.value?.open('add')
}

// 编辑
const handleEdit = async (data: any) => {
  showEdit.value = true
  await nextTick()
  editRef.value?.open('edit')
  editRef.value?.setFormData(data)
}

const editField = async (field: any, value: any, id: any) => {
  await editFieldItem({field, value, id})
  getLists()
}

const changeColor = async (data: any, index: any, name: any) => {
  editIndex.value = name + index
}
const setSave = async (data: any) => {
  await apiRoomDepartmentDeviceSave(data);
}
const newEnter = async (data: any, index: any, name: any) => {
  const val = data[name]
  if (val && val * 1 != data['get_enter'] * 1) {
    setSave(data)
  }
  if (val == '') {
    setNullInput(data, name)
  }

  const num = parseInt(index) + 1
  editIndex.value = num
  const item = name + num
  inputRefMap.value[`Input_Ref_${item}`].input.focus();

  clearInput(pager.lists[num], name);
}

const clearInput = async (row: any, key: any,) => {
  const val = row[key]
  if (val) {
    row.get_enter = val
  }
  row[key] = ''
}

const setNullInput = async (row: any, key: any,) => {
  if (row[key] == '') {
    row[key] = row.get_enter
  }
  if (row[key] != '' && row[key] * 1 != row.get_enter * 1) {
    setSave(row)
  }
}

/** 动态设置Input Ref */
const handleSetInputMap = (el: refItem, item: number, name: any) => {
  if (el) {
    const el_name = name + item
    inputRefMap.value[`Input_Ref_${el_name}`] = el;
  }
}

// 删除
const handleDelete = async (id: number | any[]) => {
  await feedback.confirm('确定要删除？')
  await apiRoomDepartmentDeviceDelete({id})
  getLists()
}

//月初始化
const monthInit = async () => {
  await feedback.confirm('确定要月初始化吗？')
  await roomDepartmentDeviceInit({})
  getLists()
}

//复制水表
const handleCopyS = async (id: number | any[]) => {
  await feedback.confirm('确定新增水表？')
  const device_type = 1;
  await roomDepartmentDeviceCopy({id, device_type})
  getLists()
}
//复制电表
const handleCopyD = async (id: number | any[]) => {
  await feedback.confirm('确定新增电表？')
  const device_type = 2;
  await roomDepartmentDeviceCopy({id, device_type})
  getLists()
}

getLists()
</script>

<style scoped>
/deep/ .current_color .el-input__wrapper {
  background-color: blanchedalmond !important;

}

.el-button {
  margin-bottom: 10px;
  margin-right: 10px;
  margin-left: 10px;
}
</style>
